﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using MvcCarConsume.Domain;
using MvcCarConsume.Domain.Entites;
using MvcCarConsume.WebUI;
using System.Globalization;
using System.Configuration;

namespace MvcCarConsume
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                null,
                "orders/add/{id}",
                new { controller = "CarCart", action = "PostCart", id = UrlParameter.Optional }, // Parameter defaults
                new { id = @"\d+" }
            );
            
            
            
            routes.MapRoute(
                null,
                "orders/index/",
                new { controller = "CarCart", action = "Index", id = UrlParameter.Optional }
                );
            routes.MapRoute(
                null,
                "orders",
                new { controller = "CarCart", action = "Index", id = UrlParameter.Optional }
                );
            routes.MapRoute(
                null,
                "orders/AddToOrder/{id}",
                new { controller = "CarCart", action = "AddToOrder", id = UrlParameter.Optional }
                );

            routes.MapRoute(
                null,
                "picshow/image/{id}",
                new { controller = "picshow", action = "image", id = UrlParameter.Optional }
                );

            routes.MapRoute(
                null,
                "view/detail/{id}",
                new { controller = "CarView", action = "Detail", id = UrlParameter.Optional }, // Parameter defaults
                new { id = @"\d+" }
            );

            routes.MapRoute(
                null,
                "view/index/{queryinfo}",
                new { controller = "CarView", action = "Index", queryinfo = UrlParameter.Optional }
                //new { queryinfo = @"\d+-\d+-\d+-\d+-\d+"}
            );

            routes.MapRoute(
                null,
                "manage",
                new { controller = "AdminView", action = "Index" }
                );

            routes.MapRoute(
                null,
                "manage/car/add",
                new { controller = "AdminView", action = "CarAdd" }
                );
            routes.MapRoute(
                null,
                "manage/car/{page}",
                new { controller = "AdminView", action = "CarsManage" ,page = UrlParameter.Optional }
                );

            routes.MapRoute(
                null,
                "manage/orders/add",
                new { controller = "AdminView", action = "OrderAdd" }
                );

            routes.MapRoute(
                null,
                "manage/orders/{page}",
                new { controller = "AdminView", action = "OrderManage", page = UrlParameter.Optional }
                );
            routes.MapRoute(
                null,
                "manage/car/edit/{id}",
                new { controller = "AdminView", action = "CarEdit", id = UrlParameter.Optional }
                );
            routes.MapRoute(
                null,
                "manage/orders/edit/{id}",
                new { controller = "AdminView", action = "OrderEdit", id = UrlParameter.Optional }
                );

            routes.MapRoute(
                null,
                "login",
                new { controller = "Account", action = "LogIn" }
                );

            routes.MapRoute(
                null,
                "register",
                new { controller = "Account", action = "Register" }
                );

            //basic controller/action url with no param
            routes.MapRoute(null,
                "{controller}/{action}",
                new { controller = "CarView", action = "home" } // Parameter defaults
            );

            

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);
            RegisterGlobalizationRoutes();
            ControllerBuilder.Current.SetControllerFactory(new ProfileControllerFactory());
        }


        protected void Session_Start(object sender, EventArgs e)
        {
            Session.Timeout = 20;
            if (Session["session"] == null)
            {
                //获取访问者的IP
                string ipAddress = Request.ServerVariables["REMOTE_ADDR"];
                //获取访问者的来源
                string ipSrc;
                //判断是否从搜索引擎导航过来的
                if (Request.UrlReferrer == null)
                {
                    ipSrc = "";
                }
                else
                {
                    //获取来源地址
                    ipSrc = Request.UrlReferrer.ToString();
                }
                //获取访问时间
                DateTime ipDatetime = DateTime.Now;
                //获取用户访问的页面
                string pageurl = Request.Url.ToString();
                //保存IP信息到数据库中
                SqlStatictcs historyservice = new SqlStatictcs(ConfigurationManager.ConnectionStrings["MvcCarDBEntities"].ConnectionString);
                historyservice.AddHistory(ipAddress, pageurl, ipSrc, ipDatetime, "");
                Session["session"] = true;
            }
            /*
            //判断访问的是否是默认页
            if (pageurl.EndsWith("IPStat.aspx"))
            {
                //锁定变量
                Application.Lock();
                //为页面访问量+1
                Application["StatCount"] = int.Parse(Application["StatCount"].ToString()) + 1;
                //解锁
                Application.UnLock();
            }

            //锁定变量 
            Session.Timeout = 10; //设定超时为10分钟
            Application.Lock();
            Application["countSession"] = Convert.ToInt32(Application["countSession"]) + 1;　　//访问总人数＋１
            Application["onlineWhx"] = (int)Application["onlineWhx"] + 1; //在线人数加＋１
            Session["login_name"] = null;
            //解锁
            Application.UnLock();
            */
        }

        /// <summary>
        /// copy and add {ci}/ before url of each non-IgnoreRouteInternal route , and register them before original route
        /// </summary>
        private void RegisterGlobalizationRoutes()
        {

            if (RouteTable.Routes == null)
                return;

            RouteCollection rc = new RouteCollection();

            //skip IgnoreRouteInternal
            var routes = RouteTable.Routes.SkipWhile(p => (p.GetType().Name == "IgnoreRouteInternal"));

            int insertpoint = RouteTable.Routes.Count() - routes.Count();

            foreach (var r in routes)
            {
                Route item = (r as Route);
                Route newitem = new Route(
                    //string.Format(@"{ci}/{0}",item.Url),
                    @"{ci}/" + item.Url,
                    new MvcRouteHandler());
                newitem.Defaults = new RouteValueDictionary(item.Defaults);

                newitem.Constraints = new RouteValueDictionary(item.Constraints);
                newitem.Constraints.Add("ci", new CulturePrefixRule());

                newitem.DataTokens = new RouteValueDictionary();
                newitem.DataTokens["Namespaces"] = item.DataTokens["Namespaces"];
                rc.Add(newitem);
            }
            foreach (var c in rc)
            {
                RouteTable.Routes.Insert(insertpoint, c);
                insertpoint += 2;
            }
        }

        private class CulturePrefixRule : IRouteConstraint
        {
            IEnumerable<string> cultureConllection = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(p => p.Name.ToLower());
            public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
            {
                if (values[parameterName] != null)
                    return cultureConllection.Contains(values[parameterName].ToString().ToLower());
                else
                    return false;
            }
        }
    }
}
